package com.calvin.study.threadsafe.sync;

import com.calvin.study.utils.Print;

import cn.hutool.core.thread.ThreadUtil;

//这是一个线程不安全的例子
//10个线程并行运行，对一个共享数据进行自增与运算，每个线程自增运算1000次
public class ThreadSafeDemo01 {
	static final int MAX_TREAD = 10;
	static final int MAX_TURN = 1000;


	public static void main(String[] args) {
		Calculate c = new Calculate();
		//ThreadUtil.concurrencyTest(MAX_TREAD, c);
		//Print.tcfo(c.getAmount());
		
		testNotSafePlus();
	}

	public static void testNotSafePlus() {
		NotSafePlus counter = new NotSafePlus();
		for (int i = 0, len = MAX_TREAD; i < len; i++) {
			new Thread(() -> {
				//System.out.println(Thread.currentThread().getName());
				for (int j = 0, length = MAX_TURN; j < length; j++) {
					counter.selfPlus();
				}
			},"Thread-"+i).start();
		}	
		int result = MAX_TURN * MAX_TREAD;
		Print.tcfo("理论结果： " + result);
		Print.tcfo("实际结果： " + counter.getAmount());
		Print.tcfo("差距是： " + (result - counter.getAmount()));
	}

}

class Calculate implements Runnable {

	private Integer amount = 0;

	public Integer getAmount() {
		return amount;
	}

	@Override
	public void run() {
		for (int i = 0, len = 1000; i < len; i++) {
			amount++;
		}
	}
}

class NotSafePlus {
	private Integer amount = 0;

	public Integer getAmount() {
		return amount;
	}

	// 自增
	public void selfPlus() {
		amount++;
	}
}
